// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
		car:{
			default:null,
			type:cc.Prefab
		},
		player:{
			default:null,
			type:cc.Sprite
		},
		dialog:{
			default:null,
			type:cc.Node
		}
		,
		speed :30,
		rate:1,
    },

    // LIFE-CYCLE CALLBACKS:

    // onLoad () {},

    start () {
		this.time = 0;
		this.nextTime = 0;
		this.startGame = false;
		var self = this;
		this.dialog.finishCallBack=function(){
			self.startGame = true;
			self.dialog.active =false;
		}
    },
	buildBalls:function(num){
		
		for (let i = 0 ;i<num;i++){
			var node = new cc.instantiate(this.car);
			try{
				node.parent = this.node;	
			}catch(err){
				node.parent = this.node;
			}
			// 设置随机起点
			var side = Math.floor(Math.random()*4);
			if (side<2){ //上下出现
				if (side===0)
					node.y=-this.node.height/2-100;
				else
					node.y =this.node.height/2+100;
				node.x = Math.floor((this.node.width)*(Math.random()-0.5));
			}else{//左右出现
				if (side===2)
					node.x=-this.node.width/2-100;
				else
					node.x =this.node.width/2+100;
				node.y = Math.floor((this.node.height)*(Math.random()-0.5));
			}
			
			//设置运动方向
			var velocity = cc.v2(this.player.node.x -node.x,this.player.node.y -node.y);
			velocity.normalizeSelf();
			velocity.mulSelf(this.speed);
			var phy = node.getComponent(cc.RigidBody);
			phy.linearVelocity = velocity;
			if (velocity.y<0){
				node.rotation = -velocity.angle(cc.v2(-1,0))*180/Math.PI;
			}else{
				node.rotation = velocity.angle(cc.v2(-1,0))*180/Math.PI;
			}	
		}
			
	},
    update (dt) {
		if (this.startGame){
			this.time+=dt;
			if (this.nextTime<=this.time){
				this.nextTime+=3;
				this.buildBalls(this.nextTime*this.rate);
			}
		}		
	},
});
